<?php
namespace mobile;
use mobile\libs\Data;
use mobile\libs\CRedis;
use mobile\libs\Curl;

date_default_timezone_set('Asia/Shanghai');
define('DIR', __DIR__);
require DIR.'/src/Boot.php';

class Master{
	protected $data = [];
	protected $childs = [];
	protected $maxChild = 4; // 子进程最大数量限制
	protected $redis;
	
	public function __construct() {
		$this->redis = CRedis::model();
		
		$this->data = Data::getDatas();
	}
	
	public function run() {
		$i = 0;
		while(true) {
			$this->redis->ping();
			$this->check();
			
			if(count($this->childs) < $this->maxChild) {
				$this->worker();
			}
			
			if(++$i > 100) {
				$i = 0;
				$this->data = Data::getDatas();
			}
			sleep(1);
		}
	}
	
	protected function getMobile() {
		return $this->redis->blpop('mobile_list', 1);
	}
	
	/**
	 * 获取需要处理的手机号，并开新进程处理
	 */
	protected function worker() {
		$data = $this->getMobile();
		if(empty($data) || !isset($data[1])) return false;
		
		echo "Run worker, Mobile: ", $data[1], "\n";
		
		// 开启分支
		$pid = pcntl_fork();
		if($pid == -1) {
			echo "Fork worker failed!";
			return false;
		}
		
		if($pid) {
			echo "Fork worker success! pid:",  $pid, "\n";
			$this->childs[] = $pid;
		} else {
			define('MOBILE', $data[1]);

			$boot = new Boot($this->data);
			$boot->run();
			
			exit();
		}
	}
	
	/**
	 * 检测子进程状态，避免僵尸进程
	 */
	protected function check() {
		foreach($this->childs as $index => $pid) {
			$pid && $res = pcntl_waitpid($pid, $status, WNOHANG);
			if(!$pid || $res == -1) {
				unset($this->childs[$index]);
			}
		}
	}
}

$master = new Master;
$master->run();
